var express = require('express')
// var request = require('superagent');
var router = express.Router()
const user = require('../utils')
const query = require('../pool')

//POST 登录
router.post('/login', (req, res) => {
 user.findOne(req.body)
  .then(data => {
    return data
  })
  .then(data => {
    if (data.length > 0) {
      if (data[0].password == req.body.password) {
        return data[0]
      } else {
        throw new Error('登录失败，请检查密码是否正确')
      }
    } else {
      throw new Error('登录失败，请检查账号是否正确')
    }
  })
  // 更新用户当前状态
  .then(async data => {
    [err] = await query(`UPDATE user SET status = 1 WHERE id = '${data.id}'`)
    if (err) {
      throw new Error(err)
    } else {
      return data
    }
  })
  // 更新用户最后一次登录时间
  .then(async data => {
    [err, lastLoginTime] = await query(`UPDATE user SET last_login = current_timestamp WHERE id = '${data.id}'`)
    if (err) {
      throw new Error(err)
    } else {
      return {
        ...data
      }
    }
  })
  // 获取用户最后一次登录时间
  .then(async data => {
    [err, data] = await query(`SELECT * FROM user WHERE id = '${data.id}'`)
    if (err) {
      throw new Error(err)
    } else {
      return data[0]
    }
  })
  // 获取动态路由菜单
  // .then(async data =>  {
  //   const [err, rows] = await query(`SELECT * FROM mapDemo`)
  //   if (err) {
  //     throw new Error(err)
  //   } else {
  //     return {
  //       ...data,
  //       menu: rows
  //     }
  //   }
  // })
  // 设置token
  .then(data => {
    return user.setToken(data.username, data.password).then((token)=>{
      return {
        id: data.id,
        token
      }
    })
  })
  // 结束逻辑
  .then(data => {
    res.send({
      code: 0,
      data
    })
  })
  .catch(e => {
    res.send({
      code: -1,
      msg: e.message
    })
  })
})

router.post('/logout', async (req, res) => {
  [err] = await query(`UPDATE user SET status = 0 WHERE id = '${data.id}'`)
  if (err) {
    throw new Error(err)
  } else {
    res.send({
      code: 0,
      msg: '退出登录成功!'
    })
  }
})

/** 根据id来获取用户 */
router.get('/getUserInfoById', async (req, res) => {
  [err, data] = await query(`SELECT * FROM user WHERE id = '${req.query.id}'`)
  if (err) {
    throw new Error(err)
  } else {
    if (data.length) {
      res.send({
        code: 0,
        data: data[0]
      })
    } else {
      res.send({
        code: -1,
        msg: '未查询到该用户!'
      })
    }
  }
})

/** 根据openId来获取用户 */
router.get('/getUserInfoByOpenId', async (req, res) => {
  [err, data] = await query(`SELECT * FROM user WHERE openId = '${req.query.openId}'`)
  if (err) {
    throw new Error(err)
  } else {
    if (data.length) {
      res.send({
        code: 0,
        data: data[0]
      })
    } else {
      res.send({
        code: -1,
        msg: '未查询到该用户!'
      })
    }
  }
})

router.post('/logout', async (req, res) => {
  [err] = await query(`UPDATE user SET status = 0 WHERE id = '${data.id}'`)
  if (err) {
    throw new Error(err)
  } else {
    res.send({
      code: 0,
      msg: '退出登录成功!'
    })
  }
})

// router.get('/getOpenid', async (req, res) => {
//   // 服务端发起请求获取用户openid等信息
//   request
//     .get('https://api.weixin.qq.com/sns/jscode2session')
//     .query({
//       appid: 'wx9512adb2c3751312',
//       secret: 'c5800ccaaade8e15042fc7aefa562a60',
//       js_code: req.query.code,
//       grant_type: 'authorization_code'
//     })
//     .then(response => {
//       res.send({
//         code: 0,
//         data: response.text
//       })
//     }).catch(res => {
//       console.log(res, '202502281050');
//     })
// })

// router.get('getPhone', async (req, res) => {
//   request
//     .get('https://api.weixin.qq.com/cgi-bin/token')
//     .query({
//       grant_type: 'client_credential',
//       appid: 'wx9512adb2c3751312',
//       secret: 'c5800ccaaade8e15042fc7aefa562a60'
//     })
//     .then(e => {
//       // 服务端发起请求
//       request
//         .post('https://api.weixin.qq.com/wxa/business/getuserphonenumber')
//         .query({
//           access_token: e.body.access_token
//         })
//         .then(response => {
//           res.send({
//             code: 0,
//             data: response.body.phone_info
//           })
//         })
//     })
// })

module.exports = router
